package cn.cosmosx.base.pdf;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import technology.tabula.*;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PDFTableReader<T> {
    // 换行符
    private final static String LINE_WRAP = "\r";
    /**
     * PDF数据缓冲器
     */
    private final List<Map<String, String>> dataBuff = new ArrayList<>();
    private final transient File pdfFile;
    /**
     * 表格标题属性
     */
    private final PDFTitle[] pdfTitles;

    /**
     * 标题所在行号
     * 默认第一行
     */
    private int titleRowIndex = 0;

    /**
     * 描述信息
     */
    private String keyInfo;
    /**
     * 关键信息所在页起始下标，从0开始
     */
    private int keyInfoPageNumber;
    /**
     * 关键信息所在行起始下标
     */
    private int keyInfoLineStartIndex;
    /**
     * 关键信息所在行结束下标
     */
    private int keyInfoLineEndIndex;
    // 表格映射实体类
    private final Class<T> beanClass;

    private PDFTableReader(File pdfFile, Class<T> beanClass) {
        this.pdfFile = pdfFile;
        this.beanClass = beanClass;
        if (beanClass == null) {
            throw new RuntimeException("必须指定读取表格数据的实体类");
        }
        Field[] fields = beanClass.getDeclaredFields();
        pdfTitles = new PDFTitle[fields.length];
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            TableTitle title = field.getAnnotation(TableTitle.class);
            if (title == null) {
                throw new RuntimeException(field.getName() + " attribute miss annotation TableTitle");
            }
            pdfTitles[i] = new PDFTitle(title.cellIndex(), title.value(), title.trimSpace());
        }
    }

    public static <T> PDFTableReader<T> load(File pdfFile, Class<T> beanClass) {
        return new PDFTableReader<T>(pdfFile, beanClass);
    }

    /**
     * 设置PDF表格标题所在行号
     *
     * @param titleRowIndex - 表头标题所在行下标，从0开始
     */
    public PDFTableReader<T> titleRowIndex(int titleRowIndex) {
        this.titleRowIndex = titleRowIndex;
        return this;
    }

    /**
     * 设置PDF描述信息
     *
     * @param keyInfoPageNumber     - 关键信息所在页起始下标，从0开始
     * @param keyInfoLineStartIndex - 关键信息所在行起始下标，从0开始
     * @param keyInfoLineEndIndex   - 关键信息所在行结束下标，从0开始
     */
    public PDFTableReader<T> describe(int keyInfoPageNumber, int keyInfoLineStartIndex, int keyInfoLineEndIndex) {
        this.keyInfoPageNumber = keyInfoPageNumber;
        this.keyInfoLineStartIndex = keyInfoLineStartIndex;
        this.keyInfoLineEndIndex = keyInfoLineEndIndex;
        return this;
    }

    public List<Map<String, String>> readMaps() {
        return this.doRead();
    }

    public List<T> readBeans() {
        List<T> beans = new ArrayList<>();
        List<Map<String, String>> maps = this.doRead();
        T bean;
        try {
            for (Map<String, String> map : maps) {
                bean = this.beanClass.newInstance();
                Field[] fields = bean.getClass().getDeclaredFields();
                for (Field field : fields) {
                    TableTitle title = field.getAnnotation(TableTitle.class);
                    if (title == null) {
                        continue;
                    }
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    field.set(bean, map.get(title.value()));
                }
                beans.add(bean);
            }
            return beans;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private List<Map<String, String>> doRead() {
        try (PDDocument document = PDDocument.load(pdfFile)) {
            // 读取描述
            this.doReadKeyInfo(document);
            // 读取表格
            List<Map<String, String>> maps = new ArrayList<>();
            SpreadsheetExtractionAlgorithm sea = new SpreadsheetExtractionAlgorithm();
            PageIterator pi = new ObjectExtractor(document).extract();
            Map<String, String> cellMap;
            int rowNum = 0;// 行计数器
            while (pi.hasNext()) {
                Page page = pi.next();
                List<Table> tables = sea.extract(page);
                for (Table table : tables) {
                    List<List<RectangularTextContainer>> rows = table.getRows();
                    if (rows.size() <= titleRowIndex) {
                        throw new RuntimeException("标题行不正确");
                    }
                    for (List<RectangularTextContainer> row : rows) {
                        if (rowNum <= titleRowIndex) {
                            rowNum++;
                            continue;
                        }
                        // 处理表格数据
                        cellMap = new HashMap<>(row.size());
                        for (int k = 0; k < row.size(); k++) {
                            RectangularTextContainer cell = row.get(k);
                            PDFTitle pdfTitle = pdfTitles[k];
                            // 如果标题列下标不匹配，跳过
                            if (pdfTitle.getCellIndex() != k) {
                                continue;
                            }
                            // 换行处理，此处需要调用
                            String cellText = cell.getText();
                            cellText = cellText == null ? "" : cellText.trim();
                            if (pdfTitle.isTrimSpace()) {
                                cellMap.put(pdfTitle.getName(), cellText.replace(LINE_WRAP, ""));
                            } else {
                                cellMap.put(pdfTitle.getName(), cellText.replace(LINE_WRAP, " "));
                            }
                        }
                        maps.add(cellMap);
                        rowNum++;
                    }
                }
            }
            this.dataBuff.addAll(maps);
            return maps;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private void doReadKeyInfo(PDDocument document) throws IOException {
        PDFTextStripper stripper = new PDFTextStripper();
        stripper.setSortByPosition(true); //sort:设置为true 则按照行进行读取，默认是false
        stripper.setStartPage(keyInfoPageNumber);
        stripper.setEndPage(keyInfoPageNumber + 1);
        String result = stripper.getText(document);
        result = result.replaceAll("\n", "");
        String[] split = result.split(LINE_WRAP);
        if (keyInfoLineStartIndex >= split.length || keyInfoLineEndIndex >= split.length) {
            throw new RuntimeException("关键信息所在列已超出读取页码行的范围");
        }
        StringBuilder r = new StringBuilder();
        for (int i = keyInfoLineStartIndex; i <= keyInfoLineEndIndex; i++) {
            String line = split[i];
            if (line == null || line.trim().equals("")) {
                continue;
            }
            r.append(line.trim());
        }
        this.keyInfo = r.toString();
    }

    public List<Map<String, String>> getDataBuff() {
        return dataBuff;
    }

    public String getKeyInfo() {
        return keyInfo;
    }

    // PDF表格标题属性
    @Getter
    @AllArgsConstructor
    static class PDFTitle {
        // 标题所在列下标，从0开始
        private int cellIndex;
        // 标题名称
        private String name;
        // 需要去掉空格
        private boolean trimSpace;
    }
}
